const request = require("request");

const weixininfo_itron = {
    APPID: "wx4e93458fd5949c2d",
    SECRET: "a74ad774f057a9dcd30b55bd2b106d6e",
}

const setToken = (req, res, cb) => {
    var code = req.query.code;
    var url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + weixininfo_itron.APPID + "&secret=" + weixininfo_itron.SECRET + "&code=" + code + "&grant_type=authorization_code";
    // console.log(url);
    request(url, (err, response, body) => {
        if (err) {
            // console.log(error);
            res.send(JSON.stringify({
                result: -1,
                msg: "登陆错误，请重试",
                // error: error
            }));

            console.error(err);
            return;
        }
        body = JSON.parse(body);
        // console.log(body);
        /*
        {"access_token":"fZiJHUwySDFLT0R4fXnloN0y7ycFNqZ6R09EXyQHryCa3bXpeXaNB5ITPj1PLiYUwNFV2csB-s3aqbgVlXTZ-ltlY_QgC274pJSqyz_T1eU",
        "expires_in":7200,
        "refresh_token":"KP0X0Dzgy_UUoLsg5Ra-4_iZdAiSr0Fpul27E6ODfrfBH1_Xg1URyjRNhuRhavzSfdnJ5-cXAGk7G25sty6_dg1NGby3ujfdgzQJF0VZ7To",
        "openid":"oiVRGwcfKpSGko_4ueiYz1R34Q2o",
        "scope":"snsapi_login",
        "unionid":"oAKOSwZTeHmeLWwIXLIj652ZKNHE"}0..0
        */
        var url2 = "https://api.weixin.qq.com/sns/userinfo?access_token=" + body.access_token + "&openid=" + body.openid;
        // console.log(url2);
        request(url2, (err, response, body2) => {
            if (err) {
                res.send(JSON.stringify({
                    result: -1,
                    msg: "登陆错误，请重试",
                    // error: error
                }));
                console.error(err);
            } else {
                /*
                {"openid":"oiVRGwcfKpSGko_4ueiYz1R34Q2o",
                "nickname":"",
                "sex":1,
                "language":"zh_CN",
                "city":"Fengtai",
                "province":"Beijing",
                "country":"CN",
                "headimgurl":"http:\\/\\/wx.qlogo.cn\\/mmopen\\/8Q7u6gJAwWc8vl5QQ0P184USKMM6skwd553HvL61UCo5ica7AgKVBVianFfReowZr6qEH8VNa3qaO84GQz6nzXwK5jU75USmUU\\/0",
                "privilege":[],
                "unionid":"oAKOSwZTeHmeLWwIXLIj652ZKNHE"}
                */
                body2 = JSON.parse(body2);
                // console.log(body2);
                var sessionStore = req.sessionStore;
                var sid = req.query.state;
                sessionStore.load(sid, (err, sess) => {
                    if (err) {
                        res.redirect(301, '/close.html');
                        console.error(err);
                    } else if (!sess) {
                        res.redirect(301, '/close.html');
                        // return;
                    } else if (body2.errcode) {
                        // console.log(body2);
                        res.send(JSON.stringify({
                            result: -1,
                            msg: "登陆错误，请重试",
                            // error: error
                        }));
                        console.error(err);
                    } else {
                        sess.userInfo = {
                            userType: "weixinItron",
                            id: "weixinItron_" + body2.openid,
                            nickname: body2.nickname,
                            verified: true,
                            prop: body2
                        };
                        sess.save((err) => {
                            if (err) {
                                console.error(err);
                            }
                        });
                        res.redirect(301, '/close.html');
                        // console.log("set token " + sess.id);
                        // console.log(sess);
                        cb(sess.userInfo);
                    }
                });
            }
        });

    });
}
module.exports.setToken = setToken;
/*
function getToken(req, res) {
    res.setHeader('Content-Type', 'application/json');
    console.log("get token " + req.sessionID);
    console.log(req.session);
    var session = req.session;
    res.send(JSON.stringify({
        result: 0
        , token: session.weixinToken
    }));
}
exports.getToken = getToken;
*/